import { defineStore } from 'pinia'
import { ref } from 'vue'
import { selectUsersService } from '@/api/user'

// 用户模块  token seToken removeToken  存储用户信息  移除用户信息  获取用户信息
export const useUserStore = defineStore(
  'love-user',
  () => {
    const token = ref('')
    const seToken = (newToken) => {
      token.value = newToken
    }
    const removeToken = () => {
      token.value = ''
    }
    //用户信息
    const user = ref({})
    //获取用户信息
    const getUser = async () => {
      return user.value
    }

    const userList = ref([])
    const fetchUserList = async (selection) => {
      try {
        const fetchedUsers = await selectUsersService({
          pageNum: selection.pageNum,
          pageSize: selection.pageSize,
          schoolId: selection?.school, // 修复参数名称：school -> schoolId
          orientation: selection?.orientation,
          majorId: selection?.major, // 确保major参数正确传递为majorId
        })
        console.log('fetchedUsers', fetchedUsers)
        userList.value = fetchedUsers.data.data.items || []
        return fetchedUsers.data.data.total || 0
      } catch (e) {
        console.error(e)
      }
    }
    const getUserList = () => {
      return userList.value
    }
    // 退出登陆清楚用户信息
    const setUser = (obj) => {
      // 将用户信息保存到本地
      user.value = obj
    }

    return {
      token,
      seToken,
      removeToken,
      user,
      getUser,
      setUser,
      userList,
      fetchUserList,
      getUserList,
    }
  },
  {
    persist: true,
    // 持久化存储的插件选项
  },
)
